package com.zhgxi.openfire;

import org.jivesoftware.smack.*;
import org.jivesoftware.smack.packet.Message;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * Created with IntelliJ IDEA.
 * User: xi
 * Date: 13-12-3
 * Time: 下午3:37
 * To change this template use File | Settings | File Templates.
 */
public class ChartToEndUser {


    public static void chatuser(final Connection conn) {
        ChatManager manager = conn.getChatManager();
        final MessageListener messagelistener = new MessageListener() {
            @Override
            public void processMessage(Chat chat, Message message) {
                System.out.println(conn.getUser() + " Received message:" + message.getBody());
            }
        };
        manager.addChatListener(new ChatManagerListener() {
            @Override
            public void chatCreated(Chat chat, boolean createdLocally) {
                if (!createdLocally) {
                    chat.addMessageListener(messagelistener);
                }
            }
        });
    }

    //主函数，与服务器连接、用户登录、发送消息都是从这里实现的
    public static void main(String[] args) {
        ConnectionConfiguration config = new ConnectionConfiguration("127.0.0.1", 5222);  //第一个参数是你的openfire服务器地址，5222是openfire通信的端口
        config.setCompressionEnabled(true);
        config.setSASLAuthenticationEnabled(true);

        Connection connection_z3 = new XMPPConnection(config);


        try {
            connection_z3.connect();
            connection_z3.login("z3", "z3");
            ChatManager chatManager = connection_z3.getChatManager();
            Chat chat = chatManager.createChat("xi@xi-pc", new MessageListener() {  //这里第一个参数是接收人的地址，不能只写用户名，具体是什么可以在上面先用System.out.println(conn.getUser());把用户的具体表示方法打印出来看看
                @Override
                public void processMessage(Chat chat,
                                           Message message) {
                    System.out.println("Received message:" + message.getBody());
                }
            });
            while (true) {

                BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
                String message = "";
                System.out.println(connection_z3.getUser() + " Please input the message:");
                try {
                    message = br.readLine();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                chat.sendMessage(message);
//                Message msg = new Message();
//                chat.sendMessage(msg);
            }
        } catch (XMPPException e) {
            e.printStackTrace();
            System.out.println("Error Delivering block");
        }

        connection_z3.disconnect();
    }

}
